import axios from 'axios'
import { ElMessage } from 'element-plus'
import useElementPlusStore from '@/stores/UseElementPlusStore'

interface ResponseModel {
  data: any
  code: BusinessEnum
  message: string
}

enum BusinessEnum {
  Failed = -1,
  ArgumentError = -2,
  Success = 0,
  BadRequest = 400,
  SystemError = 500,
}

function convertData(response: ResponseModel) {
  switch (response.code) {
    case BusinessEnum.Failed:
      ElMessage({
        showClose: true,
        message: response.message,
        type: 'error',
      })
      break
    case BusinessEnum.Success:
      return response.data
    case BusinessEnum.BadRequest:
      ElMessage({
        showClose: true,
        message: '参数异常',
        type: 'error',
      })
      break
    default:
      ElMessage({
        showClose: true,
        message: '系统异常',
        type: 'error',
      })
  }

  return null
}

const httpClient = axios.create({
  // baseURL: 'api',
  timeout: 1000,
})

httpClient.interceptors.response.use(
  function (response) {
    if (response.status != 200) {
      ElMessage({
        showClose: true,
        message: '网络异常，请稍后再试!',
        type: 'error',
      })
    } else {
      return convertData(response.data as ResponseModel)
    }
  },
  function (error) {
    useElementPlusStore().closeLoad()
    ElMessage({
      showClose: true,
      message: '真倒霉，系统异常了......',
      type: 'error',
    })
    return Promise.reject(error)
  },
)

httpClient.interceptors.request.use(
  function (config) {
    if (config.method === 'post') {
      config.headers['Content-Type'] = 'application/json'
    }

    return config
  },
  function (error) {
    return Promise.reject(error)
  },
)

export default httpClient
